import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Router, ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';
import { HttpService } from '../../../service/http.service';

@Component({
  selector: 'app-edit-page',
  templateUrl: './edit-page.component.html',
  styleUrls: ['./edit-page.component.scss'],
  providers: [ HttpService ]
})
export class EditPageComponent implements OnInit {

  public user = {user_name: '', user_realname: '', active: true, password: '', user_role: 'user'};

  private pageUserName;

  dataSource: Observable<any>;

  pageState: string; // "new" / "edit";

  errorStyle: any;
  errMsg: string;

  successStyle: any;
  successMsg: string;
  

  constructor(public activeRoute: ActivatedRoute, private router: Router, public http: Http,
              public httpService: HttpService) {
    if(activeRoute.snapshot.url[0].path == 'newUser'){
      this.pageState = 'new';
    }else{
      this.pageState = 'edit';
      this.pageUserName = this.activeRoute.snapshot.params['id'];
      // console.log("pageUserName=" + this.pageUserName);
      this.dataSource = this.http.get('/api/user/get_user?user_name=' + this.pageUserName)
                        .map(response => response.json());
    }
    console.log(activeRoute.snapshot.url);

    this.errorStyle = {'width': '250px', 'display': 'none'};

    this.successStyle = {'width': '250px', 'display': 'none'};
  }

  ngOnInit() {
    if(this.pageState == 'edit'){
      this.dataSource.subscribe(data => {
        if(data && data.length > 0){
          this.user = data[0];
          this.user['origin_user_name'] = this.user.user_name;
          this.user['password'] = '';
        }
        console.log(this.user);
      });
    }
  }

  resetError(){
    this.errorStyle.display = 'none';
  }

  resetSuccess(){
    this.successStyle.display = 'none';
  }

  setError(msg:string){
    this.errorStyle.display = 'block';
    this.errMsg = msg;
  }

  setSuccess(msg:string){
    this.successStyle.display = 'block';
    this.successMsg = msg;
  }

  validateInput():boolean{
    this.resetError();
    this.resetSuccess();
    
    if(!this.user.user_name){
      this.setError('用户登录名不能为空！');
      return false;
    }

    if(!this.user.user_realname){
      this.setError('用户名不能为空！');
      return false;
    }

    if(this.pageState == 'new' && !this.user.password){
      this.setError('新用户密码不能为空！');
      return false;
    }

    return true;
  }

  saveUser(){
    if(this.validateInput()){
      // alert('save');
      // console.log(this.pageState);
      var saveUrl: string;

      if(this.pageState == 'new'){
        saveUrl = '/api/user/add_user';
      }else{
        saveUrl = '/api/user/save_user';
      }
       
      this.httpService.postData(saveUrl, this.user).subscribe(data => {
        if(data['success']){
          this.setSuccess('保存成功');
        }else{
          this.setError(data['msg']);
        }
      }
      );
    }
  }

  back(){
    this.router.navigateByUrl('/admin');
  }

}
